<template>
  <div class="app-container">
    <div class="info-container">
      <div class="info-item">
        <span>bom编号:</span>
        <span class="content">{{ bomCode }}</span>
      </div>
      <div class="info-item">
        <span>工艺流程编码:</span>
        <span class="content">{{ routeCode }}</span>
      </div>
      <div class="info-item">
        <span>工艺流程名称:</span>
        <span class="content">{{ routeName }}</span>
      </div>
    </div>
    <el-table
        border
        v-if="refreshTable"
        v-loading="loading"
        :data="planningbomList"
        row-key="lineId"
        :default-expand-all="true"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column label="产品/物料编号" width="150" align="center" prop="productCode" :show-overflow-tooltip="true"/>
      <el-table-column label="产品/物料名称" width="180" align="left" prop="productName" :show-overflow-tooltip="true"/>
      <el-table-column label="规格型号" width="120" align="center" prop="bomSpc" :show-overflow-tooltip="true"/>
      <el-table-column label="图号" width="100" align="center" prop="remark" :show-overflow-tooltip="true"/>
      <el-table-column label="物料类型" width="80" align="center" prop="itemOrProduct" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_item_product" :value="scope.row.itemOrProduct"/>
        </template>
      </el-table-column>
      <el-table-column label="生产方式" width="80" align="center" prop="workorderType" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_workorder_type" :value="scope.row.workorderType"/>
        </template>
      </el-table-column>
      <el-table-column label="计划数量" width="80" align="center" prop="used" :show-overflow-tooltip="true"/>
      <el-table-column label="库存可用量" width="100" align="center" prop="quantityOnhand" :show-overflow-tooltip="true"/>
      <el-table-column label="工艺编号" width="200" prop="routeCode" align="center" v-if="this.attr3 == 1">
        <template #default="scope">
          <el-select v-model="scope.row.routeCode" placeholder="请选择工艺路线" @change="val => routeSelected(val, scope.row.productId)"
                     v-if="planning.productId != scope.row.productId && scope.row.workorderType != 'PURCHASE'">
            <el-option
              v-for="routeProduct in scope.row.routeProductList"
              :key="routeProduct.recordId"
              :label="routeProduct.routeCode"
              :value="routeProduct.recordId+';'+routeProduct.routeName">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="工艺编号" width="200" prop="routeCode" align="center" v-if="this.attr3 == 0"/>
      <el-table-column label="工艺名称" width="200" align="center" prop="routeName" :show-overflow-tooltip="true"/>
      <el-table-column label="工单数量" width="180" align="center" prop="quantityScheduled" fixed="right">
        <template #default="scope">
          <el-input-number v-model="scope.row.quantityScheduled" :min="scope.row.quantityOnhand < scope.row.used ? scope.row.used - scope.row.quantityOnhand : 0"
                           :max="scope.row.used"
                           size="small"/>
        </template>
      </el-table-column>
      <el-table-column label="计划开工日期" width="180" align="center" prop="startDate">
        <template #default="scope">
          <el-date-picker
              v-model="scope.row.startDate"
              type="date"
              value-format="yyyy-MM-dd"
              size="small"
              style="width: 130px"
              :picker-options="getStartDateOptions(scope.row.endDate)"
              @change="validateStartDate(scope.row)"
              placeholder="请选择日期">
          </el-date-picker>
        </template>
      </el-table-column>
      <el-table-column label="计划完工日期" width="180" align="center" prop="endDate">
        <template #default="scope">
          <el-date-picker
              v-model="scope.row.endDate"
              placeholder="请选择日期"
              size="small"
              type="date"
              value-format="yyyy-MM-dd"
              style="width: 130px"
              :picker-options="getEndDateOptions(scope.row.startDate)"
              @change="validateEndDate(scope.row)"
          />
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { addList, productList } from '@/api/mes/pro/planningbom';
import { getRouteproduct, listProRouteproduct } from "@/api/mes/pro/routeproduct";
import { fenjiePlanning2 } from "@/api/mes/pro/planning";

export default {
  name: 'Planningbom',
  dicts: ['mes_item_product', 'mes_workorder_type'],
  data() {
    return {
      productId: null,
      // 重新渲染表格状态
      refreshTable: true,
      // 遮罩层
      loading: true,
      // 生产工单BOM组成表格数据
      planningbomList: [],
      routeProductList: [],
      bomId: undefined,
      bomCode: undefined,
      bomName: undefined,
      routeCode: undefined,
      routeName: undefined,
      showFlag: false,
      recordId: undefined,
      attr3: undefined,
      // 查询参数
      queryParams: {
        planId: null,
        planCode: null
      }
    };
  },
  props: {
    planning: undefined,
    optType: undefined
  },
  watch: {
    'planning.planId': function (newPlanId, oldPlanId) {
      if (newPlanId !== oldPlanId) {
        this.getList();
      }
    },
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询生产工单BOM组成列表 */
    async getList() {
      this.loading = true;
      try {
        this.queryParams.planId = this.planning.planId;
        this.queryParams.planCode = this.planning.planCode;
        this.queryParams.itemOrProduct = 'PRODUCT';

        // 第一步：获取默认工艺路线 + BOM
        const routeResp = await getRouteproduct(this.planning.attr1);
        const routeData = routeResp.data || {};

        this.routeCode = routeData.routeCode;
        this.routeName = routeData.routeName;
        this.bomId = routeData.bomId;
        this.bomCode = routeData.bomCode;
        this.bomName = routeData.bomName;
        this.attr3 = routeData.attr3;

        // 第二步：获取产品列表
        const productResp = await productList(this.queryParams);
        let productListData = productResp.data || [];

        if(this.planning.mergeSameProduct == 'Y'){
          productListData = this.mergeList(productListData);
        }

        // 第三步：异步处理每一行，获取 routeProductList
        const planningbomList = await Promise.all(
          productListData.map(async row => {
            const quantityScheduled = row.quantityOnhand >= row.used
              ? 0
              : row.used - row.quantityOnhand;

            const newRow = {
              ...row,
              quantityScheduled
            };
            if (routeData.attr3) {
              newRow.routeProductList = await this.getRouteProductList(row.productId, row.bomId);
            }
            return newRow;
          })
        );

        // 最终赋值
        this.planningbomList = planningbomList;
      } catch (error) {
        this.$message.error('获取计划BOM数据失败');
      } finally {
        this.loading = false;
      }
    },

    validateStartDate(row) {
      if (row.startDate && row.endDate && row.endDate < row.startDate) {
        row.startDate = '' // 清空无效值
      } else {
        this.startDate = row.startDate ? new Date(row.startDate).getTime() : new Date().getTime();
      }
    },
    validateEndDate(row) {
      if (row.startDate && row.endDate && row.endDate < row.startDate) {
        row.endDate = '' // 清空无效值
      }
    },
    // 返回闭包，使每行都能单独控制禁用逻辑
    getStartDateOptions(endDate) {
      return {
        disabledDate(time) {
          if (!endDate) return false;
          const end = new Date(endDate).setHours(0, 0, 0, 0);
          return time.getTime() > end;
        }
      }
    },
    // 返回闭包，使每行都能单独控制禁用逻辑
    getEndDateOptions(startDate) {
      return {
        disabledDate(time) {
          if (!startDate) return false;
          const start = new Date(startDate).setHours(0, 0, 0, 0);
          return time.getTime() < start;
        }
      }
    },
    getRouteProductList(productId, bomId) {
      const params = {
        pageNum: 1,
        pageSize: 1000,
        itemId: productId,
        bomId: bomId,
        attr3: 1,
      };
      return listProRouteproduct(params).then(response => response.rows || []);
    },
    handleSelectRouteProduct(row) {
      this.productId = row.productId;
      this.$refs.bomItemSelect.showFlag = true;
    },
    saveTable() {
      addList(this.planningbomList).then(response => {
        if (response.code === 200) {
          fenjiePlanning2(this.planning.planId).then(response => {
            this.$emit('refreshList');
            this.$emit('close');
            this.$modal.msgSuccess('执行成功');
          });
        }
      });
    },
    onBomItemSelected(obj) {
      if (obj != undefined && obj != null) {
        for (const item of this.planningbomList) {
          if (item.productId === obj.itemId) {
            item.routeProductId = obj.recordId;
            break; // 只取第一条
          }
        }
        this.$modal.msgSuccess('选择成功');
      }
    },
    routeSelected(val, productId) {
      const recordId = val ? val.split(';')[0] : undefined;
      const routeName = val ? val.split(';')[1] : undefined;
      if (recordId != undefined && recordId != null) {
        for (const item of this.planningbomList) {
          if (item.productId === productId) {
            item.routeProductId = recordId;
            item.routeName = routeName;
            break;
          }
        }
      }
    },
    mergeList(list) {
      const map = new Map();
      list.forEach(item => {
        const key = `${item.productId}_${item.bomId}_${item.routeProductId}`;

        if (!map.has(key)) {
          const copy = { ...item };
          copy.lineIdList = [item.lineId];
          copy.parentIdList = [item.parentId];
          map.set(key, copy);
        } else {
          const existing = map.get(key);
          if (!existing.lineIdList.includes(item.lineId)) {
            existing.lineIdList.push(item.lineId);
          }
          if (!existing.parentIdList.includes(item.parentId)) {
            existing.parentIdList.push(item.parentId);
          }
          // 数值累加（注意空值保护）
          existing.used = (existing.used || 0) + (item.used || 0);
        }
      });

      return Array.from(map.values());
    }
  }
};
</script>
<style scoped>
.info-container {
  margin-top: 20px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.info-item {
  width: 30%; /* Adjust width as needed */
  margin-bottom: 10px;
}

.info-item span {
  margin-left: 10px;
}

.info-item span:first-child {
  font-family: '苹方 常规', '苹方', sans-serif;
  font-weight: 400;
  font-style: normal;
  font-size: 14px;
  color: #262626;
  text-align: left;
  line-height: 20px;
  display: inline-block;
}

.content {
  color: #8c8c8c;
  text-align: left;
}
</style>
